package com.example.sicnuaccountingapp.ui.category

import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.recyclerview.widget.GridLayoutManager
import com.example.sicnuaccountingapp.R
import com.example.sicnuaccountingapp.databinding.DialogIconPickerBinding

class IconPickerDialog : DialogFragment() {
    private var _binding: DialogIconPickerBinding? = null
    private val binding get() = _binding!!

    private var onIconSelected: ((IconItem) -> Unit)? = null

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        _binding = DialogIconPickerBinding.inflate(LayoutInflater.from(context))

        setupIconList()

        return AlertDialog.Builder(requireContext())
            .setTitle(R.string.select_icon)
            .setView(binding.root)
            .setNegativeButton(R.string.cancel, null)
            .create()
    }

    private fun setupIconList() {
        val icons = listOf(
            IconItem(R.drawable.ic_baseline_fastfood_24, "餐饮"),
            IconItem(R.drawable.ic_baseline_directions_car_24, "交通"),
            IconItem(R.drawable.ic_baseline_shopping_cart_24, "购物"),
            IconItem(R.drawable.ic_baseline_movie_24, "娱乐"),
            IconItem(R.drawable.ic_baseline_local_hospital_24, "医疗"),
            IconItem(R.drawable.ic_baseline_home_24, "住房"),
            IconItem(R.drawable.ic_baseline_school_24, "教育"),
            IconItem(R.drawable.ic_baseline_more_horiz_24, "其他")
        )

        val adapter = IconPickerAdapter(icons) { icon ->
            onIconSelected?.invoke(icon)
            dismiss()
        }

        binding.iconList.apply {
            this.adapter = adapter
            layoutManager = GridLayoutManager(context, 4)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        const val TAG = "IconPickerDialog"

        fun newInstance(onIconSelected: (IconItem) -> Unit): IconPickerDialog {
            return IconPickerDialog().apply {
                this.onIconSelected = onIconSelected
            }
        }
    }
}